import 'dart:ui';

import 'package:flutter_nb_net/flutter_net.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

import '../../../../common/constants/app_constants.dart';
import '../../../../common/log/x_logger.dart';
import '../../../../common/model/base_resp.dart';
import '../../../../common/model/options_item.dart';
import '../../../../provider/global_provider.dart';
import '../../../../utils/toast_utils.dart';
import '../../record_history/model/device_details_resp.dart';
import '../../setting/model/command_config_resp.dart';
import '../../setting/model/remote_setting_list_resp.dart';
const _hour = 60 * 60;
mixin LocationModeMixin<T extends ConsumerStatefulWidget> on ConsumerState<T> {

  // 模式
  int switchValue = -1;

  int modeOptionsIndex1 = 0;

  final modeOptions1 = [
    // 干掉10秒的选项
    // OptionsItem(label: '10秒', value: 10),
    OptionsItem(label: '30秒', value: 30),
    OptionsItem(label: '3分', value: 3 * 60),
    OptionsItem(label: '5分', value: 5 * 60),
  ];

  int modeOptionsIndex2 = 0;

  var cmdCode = 'nmset';
  DeviceDetails? deviceDetails;

  bool loadOver = false;

  final modeOptions2 = [
    OptionsItem(label: '1小时', value: 1 * _hour),
    OptionsItem(label: '2小时', value: 2 * _hour),
    OptionsItem(label: '6小时', value: 6 * _hour),
    OptionsItem(label: '12小时', value: 12 * _hour),
    OptionsItem(label: '24小时', value: 24 * _hour),
  ];

  String getCommand() {
    // 拼接指令内容
    if (switchValue == 0) {
      // 智能模式
      return '${cmdCode},${switchValue},${modeOptions1[modeOptionsIndex1].value}';
    }else if (switchValue == 1) {
      // 省电模式
      return '${cmdCode},${switchValue},${_hour}';
    }else if (switchValue == 2){
      return 'nmset,1,0';
    }else {
      return 'nmset,0,10';
    }
  }

  Future<RemoteSettingData?> getCommandConfig(String cmdCode) async {
    final queryParams = {
      'cmdCode': cmdCode,
    };
    final res = await get<CommandConfigResp, CommandConfigResp>(
        '/command/config',
        queryParameters: queryParams,
        decodeType: CommandConfigResp());
    return res.when<RemoteSettingData?>(success: (CommandConfigResp resp) {
      if (resp.code == 200) {
        return resp.data!;
      }
      return null;
    }, failure: (String msg, int code) {
      return null;
    });
  }

  kaiji() async{  // 开机
    final deviceInfo = ref.read(deviceInfoProvider);

    final postData = {
      'imei': deviceInfo.imei,
      'content': 'Offline,0',
      'cmdCode': 'Offline',
    };
    final res = await post<BaseResp, BaseResp>('/command/send', data: postData, decodeType: BaseResp());
    res.when(success: (resp) async {
      // ToastUtils.dismissLoading();
      if (resp.code == 200) {
        onSendCommandClickCallback(getCommand());
      } else {

      }
    }, failure: (String msg, int code) {

      XLogger.error('发送指令失败: msg: $msg, code: $code');
    });
  }
    onSendCommandClick(Function() success,Function() fail) async{
    final deviceInfo = ref.read(deviceInfoProvider);
    XLogger.info('获取用户指令配置');

    final res = await get<BaseResp, BaseResp>('$newBaseULr/device/model/update?imei=${deviceInfo.imei}&value=$switchValue',decodeType: BaseResp());
    res.when(success: (resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        deviceInfo.deviceMode = switchValue;
        success();
      } else {
        fail();
      }
    }, failure: (String msg, int code) {
      fail();
      XLogger.error('发送指令失败: msg: $msg, code: $code');
    });
  }

  onSendCommandClickCallback(String cmdContent) async {
    XLogger.info('发送指令: $cmdContent');
    final deviceInfo = ref.read(deviceInfoProvider);
    final postData = {
      'imei': deviceInfo.imei,
      'content': cmdContent,
      'cmdCode': cmdContent.split(',')[0],
    };
    ToastUtils.showLoading(status: '发送中...');
    final res = await post<BaseResp, BaseResp>('/command/send', data: postData, decodeType: BaseResp());
    res.when(success: (resp) async {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        // 如果是远程关闭 ，就在发送一个 db,0
        // if (cmdContent.split(',')[0] == "Offline" && cmdContent.split(',')[1] == "1") {
        //   final res =
        //   await post<ReadFileResp, ReadFileResp>('$newBaseULr/device/command',
        //       data: {'imei':deviceInfo.imei,'securityStatus':'0'},
        //       decodeType: ReadFileResp());
        //   res.when(success: (resp) async {
        //     ToastUtils.showToast('发送成功');
        //
        //   }, failure: (String msg, int code) {
        //     ToastUtils.dismissLoading();
        //     XLogger.error('设备录音文件已读失败：msg: $msg, code: $code');
        //   });
        // }else {

        onSendCommandClick(() {
          ToastUtils.showToast('发送成功');
        },() {
          ToastUtils.showToast('存储模式失败');
        });

        // }
      } else {
        ToastUtils.showToast(resp.msg ?? '发送失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('发送指令失败: msg: $msg, code: $code');
      ToastUtils.showToast('发送指令失败: msg: $msg, code: $code');

    });
  }
  // onSendCommandClickCallback(String cmdContent, {Function(bool)? result}) async {
  //   XLogger.info('发送指令: $cmdContent');
  //   final deviceInfo = ref.read(deviceInfoProvider);
  //   final postData = {
  //     'imei': deviceInfo.imei,
  //     'content': cmdContent,
  //     'cmdCode': cmdContent.split(',')[0],
  //   };
  //   // 一键重启的指令作特殊处理，实际换成立即定位指令
  //   if (cmdContent == 'reset') {
  //     postData['cmdCode'] = 'c';
  //     postData['content'] = 'c';
  //   }
  //   ToastUtils.showLoading(status: '发送中...');
  //   final res = await post<BaseResp, BaseResp>('/command/send',
  //       data: postData, decodeType: BaseResp());
  //   res.when(success: (resp) {
  //     ToastUtils.dismissLoading();
  //     if (resp.code == 200) {
  //       if(result != null){
  //         result(true);
  //       }
  //       ToastUtils.showToast('发送成功');
  //     } else {
  //       if(result != null){
  //         result(false);
  //       }
  //       ToastUtils.showToast(resp.msg ?? '发送失败');
  //     }
  //   }, failure: (String msg, int code) {
  //     if(result != null){
  //       result(false);
  //     }
  //     XLogger.error('发送指令失败: msg: $msg, code: $code');
  //     ToastUtils.showToast('发送指令失败: msg: $msg, code: $code');
  //   });
  //
  //
  // }

  @override
  void updateCmdContent(String cmdContent) async{
    XLogger.info(cmdContent);
    if (cmdContent.isEmpty) {
      final deviceInfo = ref.read(deviceInfoProvider);
      final res = await get<BaseResp, BaseResp>('$newBaseULr/device/model/list?imei=${deviceInfo.imei}',decodeType: BaseResp());
      res.when(success: (resp) {
        ToastUtils.dismissLoading();
        if (resp.code == 200) {
          // switchValue = resp.data;
          if (resp.data == null) {
            switchValue = 0;
          }else {
            switchValue = resp.data;
          }

          // ToastUtils.showToast('发送成功');
        } else {

        }
        setState(() {
          loadOver = true;
        });
      }, failure: (String msg, int code) {
        XLogger.error('发送指令失败: msg: $msg, code: $code');
        setState(() {
          loadOver = true;
        });
      });
      return;
    }
    final cmdContentList = cmdContent.split(',');
    final deviceInfo = ref.read(deviceInfoProvider);
    final res = await get<BaseResp, BaseResp>('$newBaseULr/device/model/list?imei=${deviceInfo.imei}',decodeType: BaseResp());
    res.when(success: (resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        if (resp.data == null) {
          switchValue = int.parse(cmdContentList[1]);
        }else {
          switchValue = resp.data;
        }
        if (cmdContent == "nmset,1,0") {
          switchValue = 2;
        } else
        //如果接口1 和接口2 模式状态不一样，取设备模式
        if (resp.data != int.parse(cmdContentList[1]) && resp.data == 0) {
             switchValue = int.parse(cmdContentList[1]);
         }
        if (switchValue == 3 && deviceDetails?.positionStatus == 0) {
          switchValue = 0;
        }
        XLogger.info(switchValue);
        if (switchValue == 0) {
          // 智能模式
          var index = modeOptions1.indexWhere((element) => element.value == int.parse(cmdContentList[2]));
          XLogger.info(index);
          if (index == -1) {

          }else {
            modeOptionsIndex1 = index;
          }
        } else if (switchValue == 1){
          // 省电模式
          var index = modeOptions2.indexWhere((element) => element.value == int.parse(cmdContentList[2]));
          XLogger.info(index);
          if (index != -1) {
          }else {
            modeOptionsIndex2 = index;
          }
        }
        // ToastUtils.showToast('发送成功');
      } else {

      }
      setState(() {
        loadOver = true;
      });
    }, failure: (String msg, int code) {
      XLogger.error('发送指令失败: msg: $msg, code: $code');
      setState(() {
        loadOver = true;
      });
    });
    return;

    XLogger.error(cmdContentList[1]);


    XLogger.error(switchValue);

    if (deviceInfo.deviceStatus == 4) {
      switchValue = 2;

    }else {
      switchValue = int.parse(cmdContentList[1]);

      if (switchValue == 0) {
        // 智能模式
        var index = modeOptions1.indexWhere((element) => element.value == int.parse(cmdContentList[2]));
        if (index == -1) {
          modeOptionsIndex1 = index;
        }
      } else {
        // 省电模式
        var index = modeOptions2.indexWhere((element) => element.value == int.parse(cmdContentList[2]));
        if (index != -1) {
          modeOptionsIndex2 = index;
        }
      }
    }
  }

}